package com.woniu.inlet.web.controller;

import com.woniu.exception.UserException;
import com.woniu.inlet.web.command.LoginCommand;
import com.woniu.inlet.web.command.RegisterCommand;
import com.woniu.inlet.web.fo.UserFo;
import com.woniu.inlet.web.vo.UserVo;
import com.woniu.outlet.mysql.dao.UserDao;
import com.woniu.response.ResponseResult;
import com.woniu.service.UserService;
import com.woniu.service.domain.UserDo;
import com.woniu.utils.AppUtils;
import com.woniu.utils.JwtTokenUtil;
import com.woniu.utils.LoginPass;
import com.woniu.utils.SmsMessageComponent;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@CrossOrigin
@RestController
@Api("登录注册的接口")
public class UserLoginController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SmsMessageComponent smsMessageComponent;

    @Autowired
    private UserService userService;


    @GetMapping("/user/verify")
    @ApiOperation("获取验证码")
    public ResponseResult<String> getVerify(String phonenumber) {
        if (!AppUtils.isPhonenumber(phonenumber)) {
            return new ResponseResult<>(200, "您输入的正确的电话号码");
        }
        //生成验证码 并存redis
        String verify = UUID.randomUUID().toString().substring(0, 4);
        // stringRedisTemplate.opsForValue().set(phonenumber, verify, 60 * 15, TimeUnit.SECONDS);
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(phonenumber, verify, 60 * 15, TimeUnit.SECONDS);
        if (!aBoolean) {
            return ResponseResult.ok("验证码已发送，15分钟内有效，请勿重复提交");
        }
        Map<String, String> querys = new HashMap<>();
        querys.put("receive", phonenumber);
        querys.put("tag", verify);
        querys.put("templateId", "M09DD535F4");
        String s = smsMessageComponent.sendMessage(querys);
        if (s.equals("") || s == null) {
            return ResponseResult.fail("发送验证码失败");
        } else {
            return ResponseResult.ok("发送验证码成功");
        }
    }

    @PostMapping("/user/register")
    @ApiOperation("注册测试方法")
    public ResponseResult<Object> register(@RequestBody UserFo userFo) {
        if (StringUtils.isEmpty(userFo.getPhonenumber())) {
            return ResponseResult.fail("手机号码不能为空！");
        }
        String verifyCode = stringRedisTemplate.opsForValue().get(userFo.getPhonenumber());
        if (!userFo.getVerify().equals(verifyCode)) {
            return ResponseResult.fail("验证码不正确");
        }
        Boolean delete = stringRedisTemplate.delete(userFo.getPhonenumber());

        try {
            RegisterCommand registerCommand = new RegisterCommand(userFo);
            registerCommand.execute();
            return ResponseResult.ok("注册成功！");
        } catch (Exception e) {
            if (e instanceof UserException) {
                return ResponseResult.fail(e.getMessage());
            } else {
                e.printStackTrace();
                return ResponseResult.fail("系统维护中，请稍后在试");
            }
        }
    }

    @PostMapping("/user/login")
    @ApiOperation("登录测试方法")
    public ResponseResult<Object> userLogin(@RequestBody UserFo userFo) {
        try {
            log.debug("userfo对象是：{}", userFo.toString());
            LoginCommand loginCommand = new LoginCommand(userFo);
            UserDo userDo = loginCommand.execute();

            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(userDo, userVo);
            //生成token
            String token = JwtTokenUtil.createSign(userVo.getPhonenumber(), "user");
            userVo.setToken(token);

            log.debug("将要发送给前端的前端对象是：{}", userVo);
            stringRedisTemplate.opsForValue().set(token, userVo.getId().toString(), 30, TimeUnit.MINUTES);

            return ResponseResult.ok(userVo);
        } catch (Exception e) {
            if (e instanceof UserException) {
                return ResponseResult.fail(e.getMessage());
            } else {
                return ResponseResult.fail("系统维护中，请稍后再登录");
            }
        }
    }

    @PostMapping("/user/password")
    @ApiOperation("用户登录的密码修改功能")
    public ResponseResult<Object> userEdit(@RequestBody UserFo userFo) {
        try {
            userService.updatePassword(userFo);
            return ResponseResult.ok("密码修改成功，请重新登录！！！");
        } catch (Exception e) {
            return ResponseResult.fail("系统维护中，修改密码失败！！");
        }
    }

    @PostMapping("/user/verifypassword")
    @ApiOperation("验证登录密码是否正确")
    public ResponseResult<Object> verifypassword(@RequestBody UserFo userFo) {
        boolean b = userService.verifypassword(userFo);
        if (b)
            return ResponseResult.ok("true");
        else
            return ResponseResult.ok("false");
    }

    @PostMapping("/user/certificated")
    @ApiOperation("用户实名认证功能")
    public ResponseResult<Object> userCertificated(@RequestBody UserFo userFo) {
        try {
            userService.certificated(userFo);
            return ResponseResult.ok("认证成功！！！");
        } catch (Exception e) {
            if (e instanceof UserException) {
                return new ResponseResult<>(200, e.getMessage());
            }
            return ResponseResult.fail("认证系统维护中。。");

        }
    }


    @PostMapping("/user/verifyPayPassword")
    //@ApiOperation("验证支付密码是否正确")
    public ResponseResult<Object> verifyPayPassword(@RequestBody UserFo userFo) {
        boolean b = userService.verifyPayPassword(userFo);
        if (b)
            return ResponseResult.ok("true");
        else
            return ResponseResult.ok("false");
    }

    @PostMapping("/user/payPassword")
    // @ApiOperation("修改支付密码")
    public ResponseResult<Object> editPayPassword(@RequestBody UserFo userFo) {
        try {
            userService.updatePayPassword(userFo);
            return ResponseResult.ok("修改支付密码成功！！！");
        } catch (Exception e) {
            return ResponseResult.fail("系统维护中，修改支付密码失败！！！");
        }
    }

    @GetMapping("/user/token/check")
    @ApiOperation("登录token角色判断")
    public String tokenCheck(@RequestParam("token") String token) {
        try {
            return JwtTokenUtil.getAdmin(token);
        } catch (Exception e) {
            return "token非法";
        }
    }


}
